using System.Diagnostics;
using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Rendering;
using Unity.Transforms;

partial struct PlayerSystem : ISystem
{
    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        EntityReferences entityReferences = SystemAPI.GetSingleton<EntityReferences>();
        foreach ((
            RefRW<LocalTransform> localTransform, 
            RefRW<Player> player,
            RefRW<PhysicsVelocity> physicsVelocity,
            Entity entity) 
            in SystemAPI.Query<
                RefRW<LocalTransform>, 
                RefRW<Player>,
                RefRW<PhysicsVelocity>>().WithEntityAccess())
        {


            player.ValueRW.curPos = localTransform.ValueRO.Position;
            localTransform.ValueRW.Rotation = new float4(0, 0, 0, 1);
            localTransform.ValueRW.Position.y = 0.1f;
            if (player.ValueRO.onShoot)
            {
                float3 bulletDir = player.ValueRO.shootDir;
                Entity bulletEntity = state.EntityManager.Instantiate(entityReferences.bulletEntity);
                
                BulletMover bulletMover = new BulletMover
                {
                    moveDir = player.ValueRO.shootDir,
                    moveSpeed = 60
                };
                state.EntityManager.SetComponentData(bulletEntity, bulletMover);
                SystemAPI.SetComponent(bulletEntity, 
                    LocalTransform.FromPositionRotationScale(
                        localTransform.ValueRO.Position + new float3(0, 0.5f, 0), 
                        quaternion.LookRotation(player.ValueRO.shootDir, math.up()), 
                        2f));
            }
        }   
    }
}
